<template>
  <div>
    <!--面包屑区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片区域-->
    <el-card>
      <el-row>
        <el-col :span="5">
          <el-button type="primary">新增角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item1, i1) in scope.row.children"
                    :class="['bdbotton', i1 === 0 ? 'bdtop' : '', 'vcenter']"
                    :key="item1.id">
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)">{{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row v-for="(item2, i2) in item1.children" :class="[i2 !== 0 ? 'bdtop' : '', 'vcenter']"
                        :key="item2.id">
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      type="success">{{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <el-col :span="18">
                    <el-tag v-for="item3 in item2.children"
                            closable
                            @close="removeRightById(scope.row, item3.id)"
                            type="warning" :key="item3.id">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!--<pre>
              {{scope.row.children}}
            </pre>-->
          </template>
        </el-table-column>
        <!--索引-->
        <el-table-column lable="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
            <el-button type="warning" size="mini"
                       @click="openAllocateDialog(scope.row)"
                       icon="el-icon-setting">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--分配角色对话框-->
    <el-dialog
      title="分配权限"
      :visible.sync="allocateDialogVisible"
      @close="closeAllocateDialog"
      width="50%">
      <el-tree :data="rightList"
               default-expand-all
               show-checkbox
               node-key="id"
               :default-checked-keys="checkedRightKeys"
               ref="rightDialogRef"
               :props="rightProps"></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="allocateDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allocateRight">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
    export default {
        data() {
            return {
                roleList: [],
                allocateDialogVisible: false,
                rightList: [],
                rightProps: {
                    label: 'authName',
                    children: 'children'
                },
                checkedRightKeys: [],
                roleId: '',
            }
        },
        created() {
            this.getRoleList()
        },

        methods: {
            async getRoleList() {
                const {data: res} = await this.$http.get('/roles')
                if (res.meta.status !== 200) {
                    return this.$message.error('获取角色列表失败')
                }
                this.roleList = res.data
                console.log(this.roleList)
            },
            async removeRightById(role, rightId) {
                const confirmRes = await this.$confirm('是否确认删除权限?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)

                if (confirmRes !== 'confirm') {
                    return this.$message.info('以取消删除')
                }
                const {data: res} = await this.$http.delete(`roles/${role.id}}/rights/${rightId}`)
                if (res.meta.status !== 200) {
                    return this.$message.error("删除权限失败")
                }
                this.$message.success('删除全程成功')
                // 不调用this.getRoleList()方法，因为调用这个方法整个table会重新渲染
                role.children = res.data
            },
            // 打开分配权限对话框
            async openAllocateDialog(role) {
                this.roleId = role.id
                const {data: res} = await this.$http.get('/rights/tree')
                if (res.meta.status !== 200) {
                    return this.$message.error('获取权限裂变失败')
                }
                this.rightList = res.data
                // console.log(this.roleList)
                // 将role 的叶子节点放入checkedRightKeys中，方便回显
                this.getLeafNode(role, this.checkedRightKeys)
                this.allocateDialogVisible = true
            },

            // 通过递归的方式存放叶子节点
            getLeafNode(node, arr) {
                // 将叶子节点放入arr中
                if (!node.children) {
                    return arr.push(node.id)
                }
                node.children.forEach(e => this.getLeafNode(e, arr))
            },

            // 关闭分配权限对话框时清除checkedRightKeys
            closeAllocateDialog() {
                this.checkedRightKeys = []
            },
            // 分配权限
            async allocateRight() {
                const keys = [...this.$refs.rightDialogRef.getCheckedKeys(),
                    ...this.$refs.rightDialogRef.getHalfCheckedKeys()]
                console.log(keys)
                let keyStr = keys.join(',');
                const {data: res} = await this.$http.post(`/roles/${this.roleId}/rights`, {rids: keyStr})
                if (res.meta.status !== 200) {
                      return this.$message.error(res.meta.msg)
                }
                this.$message.success(res.meta.msg)
                this.getRoleList()
                this.allocateDialogVisible = false
            },
        }
    }
</script>

<style scoped>
  .el-tag {
    margin: 7px
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbotton {
    border-bottom: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
